LOGOUT
HELP
Richard Blum
Printing This Lesson
Select what you’d like to include when you print, and then click the Print Lesson button:
Text, images, and interactive elements (Note: Only IE will print Flash elements.)
Text and images only
Text only
Saving This Lesson
For instructions on saving this lesson (shown below), please select the browser you're using.
Introduction
Congratulations, you've made it to the last lesson! We've covered a lot of ground since the start of this course. The Food Store application is complete and provides you with a template for creating your own Web store application.
To finish the course, let's discuss an advanced PHP topic—object-oriented programming (OOP). OOP is a hot topic these days, and knowing the basics of it can take your programming career to the next level.
First, we'll discuss what OOP is and what it can do for you in your Web application programming. Next, you'll learn how to incorporate OOP in PHP code and see how to create and use your own OOP classes.
Finally, we'll take a look at an advanced PHP library for interacting with the MySQL server using OOP techniques.
By the end of today, you should have a good foundation in OOP and be ready to incorporate it in your new Web applications. Let's go on to Chapter 2 and get started.
Object-Oriented Programming Basics
Before you can start working on OOP coding, you need to know how OOP works. OOP uses a completely different paradigm than how you've been coding so far. This requires that you think differently about how your programs work and how you code them.
So far, you've been writing our PHP code using the procedural style of programming. In the procedural style of programming, you create variables and functions within your PHP code to perform certain procedures, such as retrieve data records from the MySQL database and display them on a Web page. The data that you use and the functions you create are completely separate entities with no specific relation to each other.
In OOP, everything is related to a class. A class defines the characteristics of an object that you're using in your application. Every application revolves around handling objects. Our Food Store application revolves around handling three objects: products, customers, and orders.
OOP classes define the objects that your application uses. Each class contains both the data and functions required to interact with the object. Once you define the objects, all your application code needs to do is use the data and functions defined for the objects to process and manipulate them.
The benefit to OOP is that once you create a class for an object, you can use that same object anytime in any other application, because you already have the code handy for using that object. You just plug in the class definition code, and you can use it in your application.
An OOP class is comprised of members. There are two types of members. Class properties define attributes for the object (such as the description, price, and quantity in stock of a product). A class can contain many different property members with each property describing a different feature of the object.
The other type of class member is methods. A class method is similar to the standard PHP functions that you've already been using. Just like a function, the method performs an operation using the properties you define in the class. You create class methods to perform specific functions on the class data, such as a method to buy a product (where you subtract a value from the quantity property) or change the price of the product (where you add or subtract a value to the price property). Each class should be self-contained. The methods in a class should only operate on properties within the class and shouldn't deal with properties in other classes.
Creating a Class in PHP
If your head is spinning right now, don't worry. Hopefully we can clear this up by looking at some code. The first thing you need to do in OOP is create a class. You do that by using a class definition. The class definition declares all the members that comprise the class, both properties and methods. Here's an example of a simple class definition in PHP:
class Product { public $description; public $price; public $quantity; public $onsale;
public function buyProduct($amount) { $this->quantity -= $amount; } }
This class defines four property members and one method member. Each member is defined using one of three visibility classifications. The visibility of a member determines where you can use or reference that member. There are three visibility keywords used in PHP:
The Product class example declares all of the members as public, so you can reference them anywhere in your PHP code.
The buyProduct() method uses an odd variable name in the function, $this->quantity. The $this variable is a special identifier that references the current class object. In this example, it points to the $quantity property of the class. Notice the removal of the dollar sign from the quantity variable when referencing it this way. This helps PHP know that you're referencing the $quantity variable from within the class.
Now, let's take a look at how to create an actual object using the Product class.
Warning: Between PHP versions 4.x and 5.x PHP vastly changed the way to define and use classes. The use of the code in this lesson follows the PHP version 5 standards. If you're using a PHP version 4.x server, please consult the PHP online manual for how to create and use classes. You can find the URL for that section of the manual in the Supplemental Material section of this lesson.
Creating Objects
Your PHP code uses the class definition to define objects. Instantiating is the process of creating an object using a class definition. Once you instantiate a class into an object, you can use the object within your application code to reference properties and methods. To instantiate an object in PHP code, you use the following format:
$prod1 = new Product();
This creates the object called $prod1 using the Product class. Once you instantiate an object, you can access the public members of that class from anywhere in your application:
$prod1->description = "carrot"; $prod1->price = 1.50; $prod1->quantity = 10;
This code sets values for the properties of this object. Notice that you must use the -> symbol to reference the property of the object. The $prod1 variable now contains these values for the properties, and you can use them anywhere within your application code to reference these values. The same applies when you need to use a public method of an object:
$prod1->buyProduct(4);
This calls the buyProduct() method, passing the value 4. Since the buyProduct() method alters the $quantity value in the object, the next time you reference $prod1->quantity, it'll have the value 6.
Writing OOP Code in PHP
Let's write an example program using the Products class so we can see OOP in action. Just follow these steps:
<?php class Product { public $description; public $price; public $quantity; public function printProduct() { echo "Product: $this->description<br>\n"; printf("Price: $%.2f<br>\n", $this->price); echo "Quantity: $this->quantity<br>\n"; } public function buyProduct($amount) { $this->quantity -= $amount; }}$prod1 = new Product(); $prod1->description = "Carrots"; $prod1->price = 1.50; $prod1->quantity = 10; echo "Just added product:<br>\n"; $prod1->printProduct();echo "<br>Buying 4 carrots.\n"; $prod1->buyProduct(4); echo "Quantity is now: $prod1->quantity<br>\n"; ?>
public function printProduct() { echo "Product: $this->description<br>\n"; printf("Price: $%.2f<br>\n", $this->price); echo "Quantity: $this->quantity<br>\n"; }
public function buyProduct($amount) { $this->quantity -= $amount; }
}
$prod1 = new Product(); $prod1->description = "Carrots"; $prod1->price = 1.50; $prod1->quantity = 10; echo "Just added product:<br>\n"; $prod1->printProduct();
echo "<br>Buying 4 carrots.\n"; $prod1->buyProduct(4); echo "Quantity is now: $prod1->quantity<br>\n"; ?>
This example defines the Product class, which contains the four properties we discussed, plus two class methods: the buyProduct() method you've already seen and the printProduct() method. The printProduct() method is a quick way to print the property values of the Product object. You can use this method anytime you need to display the object values in your application.
That covers the bare basics of OOP. Now you can say you've written and used an OOP program! Let's move on to Chapter 3 and look at some more features of OOP.
Expanding on OOP
The simple OOP example we created isn't necessarily the best way to create a class and use it. In that example, you created all of the properties using the public classification. This means that any application that uses the Product class can directly access the properties and modify them with whatever values it wants. That could be dangerous, and it's somewhat frowned upon in OOP circles. What if a wayward application set the price property of a product to a negative value? OOP allows you to be able to code your classes to help prevent accidents like that from happening.
The preferred way to handle properties in a class is to make them private so any external code can't change them. It then creates public methods that allow programs to set and get the property values. You can control exactly what happens to the properties in those public methods. Let's create another example that demonstrates this technique:
<?phpclass Product { private $description; private $price; private $quantity; public function setDescription($value) { $this->description = $value; } public function getDescription() { return $this->description; } public function setPrice($value) { if ($value > 0) $this->price = $value; else $this->price = 0; } public function getPrice() { return $this->price; } public function setQuantity($amount) { $this->quantity = $amount; } public function getQuantity() { return $this->quantity; } public function printProduct() { echo "Product: $this->description<br>\n"; printf("Price: $%.2f<br>\n", $this->price); echo "Quantity: $this->quantity<br>\n"; } public function buyProduct($val) { $this->quantity -= $val; } }$prod1 = new Product(); $prod1->setDescription("Carrot"); $prod1->setPrice(1.50); $prod1->setQuantity(10);echo "Just added product:<br>\n"; $prod1->printProduct();echo "<br>Buying 4 carrots.\n"; $prod1->buyProduct(4); echo "Quantity is now: " . $prod1->getQuantity() . "<br>\n";?>
class Product { private $description; private $price; private $quantity;
public function setDescription($value) { $this->description = $value; } public function getDescription() { return $this->description; }
public function setPrice($value) { if ($value > 0) $this->price = $value; else $this->price = 0; } public function getPrice() { return $this->price; }
public function setQuantity($amount) { $this->quantity = $amount; } public function getQuantity() { return $this->quantity; }
public function buyProduct($val) { $this->quantity -= $val; } }
$prod1 = new Product(); $prod1->setDescription("Carrot"); $prod1->setPrice(1.50); $prod1->setQuantity(10);
echo "Just added product:<br>\n"; $prod1->printProduct();
echo "<br>Buying 4 carrots.\n"; $prod1->buyProduct(4); echo "Quantity is now: " . $prod1->getQuantity() . "<br>\n";
?>
Notice that the new methods set the property values inside the class. Only they're allowed to access the properties directly. If you try using the code:
$prod1->quantity = 10;
in your application, you'll get an error message, since the properties are now private. This provides a basic level of protection for your data. You can put any type of checks in the methods that set property values. The setPrice() method demonstrates this feature by checking the value that the program code assigns to the price property.
There's one downside to protecting your class properties, though. Now it's somewhat of a pain to create a new class object, because you have to use the individual set methods to define each property value. Fortunately, PHP provides an easy way to solve this problem.
Class Constructors
Most OOP languages provide a special method called a constructor. The constructor allows you to automatically define property values when you instantiate an object. PHP uses the special method __construct() to define the constructor:
public function __construct($name, $value, $amount) { $this->description = $name; if ($value > 0) $this->price = $value; else $this->price = 0; $this->quantity = $amount; }
The constructor for our Product class uses three parameters to assign values to the three class properties when you instantiate an object. Now, to create a new Product object, you must use this format:
$prod1 = new Product("Carrot", 1.50, 10);
You can now use a constructor to force the program code to set the class properties when it instantiates the object. If you choose, you can also block any properties from changing by not providing methods that change the values. That's a lot of control over your code!
Let's play with this concept a little. Follow these steps to build both a class file and an application file:
<?phpclass Product { private $description; private $price; private $quantity; public function __construct($name, $value, $amount) { $this->description = $name; if ($value > 0) $this->price = $value; else $this->price = 0; $this->quantity = $amount; } public function setDescription($value) { $this->description = $value; } public function getDescription() { return $this->description; } public function setPrice($value) { if ($value > 0) $this->price = $value; else $this->price = 0; } public function getPrice() { return $this->price; } public function setQuantity($amount) { $this->quantity = $amount; } public function getQuantity() { return $this->quantity; } public function printProduct() { echo "Product: $this->description<br>\n"; printf("Price: $%.2f<br>\n", $this->price); echo "Quantity: $this->quantity<br>\n"; } public function buyProduct($amount) { $this->quantity -= $amount; } public function addProduct($amount) { $this->quantity += $amount; } } ?>
public function addProduct($amount) { $this->quantity += $amount; } } ?>
<?phpinclude("Product.inc.php");$prod1 = new Product("Carrots", 1.50, 10); echo "Just added product:<br>\n"; $prod1->printProduct();$prod2 = new Product("Onions", 2.00, 15); echo "<br>Just added product:<br>\n"; $prod2->printProduct();echo "<br>Buying 4 carrots.\n"; $prod1->buyProduct(4); $quant = $prod1->getQuantity(); echo "Quantity is now: $quant<br>\n";echo "Buying 3 onions.\n"; $prod2->buyProduct(3); $quant = $prod2->getQuantity(); echo "Quantity is now: $quant<br>\n";echo "Adding 10 more carrots.\n"; $prod1->addProduct(10); $quant = $prod1->getQuantity(); echo "Quantity is now: $quant<br>\n"; ?>
include("Product.inc.php");
$prod1 = new Product("Carrots", 1.50, 10); echo "Just added product:<br>\n"; $prod1->printProduct();
$prod2 = new Product("Onions", 2.00, 15); echo "<br>Just added product:<br>\n"; $prod2->printProduct();
echo "<br>Buying 4 carrots.\n"; $prod1->buyProduct(4); $quant = $prod1->getQuantity(); echo "Quantity is now: $quant<br>\n";
echo "Buying 3 onions.\n"; $prod2->buyProduct(3); $quant = $prod2->getQuantity(); echo "Quantity is now: $quant<br>\n";
echo "Adding 10 more carrots.\n"; $prod1->addProduct(10); $quant = $prod1->getQuantity(); echo "Quantity is now: $quant<br>\n"; ?>
The Product.inc.php file contains the class definition code for the Product class. Putting the class definition code in a separate file is a common practice that allows you to use the class in any PHP program you want. Naming the file the same as the class name isn't necessary, but it sure makes life easier! All you have to do is use the include() function to bring the class definition code into your application code. Once you include the class definition, you can use it to create as many class objects as you need to handle your data.
In the next chapter, you'll see how to extend OOP classes and use that technique to get fancy with accessing the MySQL server.
Extending Classes
No, I'm not talking about trying to make your course longer! OOP provides a way to extend an existing class by adding additional functionality. That's the whole beauty of OOP. You can take classes and use them as-is, or you can modify just the pieces you need to fit a situation.
Defining a new class that's an extension of another class is called inheritance. The new class (called the child) inherits all of the members of the original class (called the parent). You can then add new members to the child class and even overwrite members of the parent class. If you use the overwritten members, the child members take precedence over the parent members.
To create a class extension, you use the class definition format, along with the extends keyword and the name of the class you're extending:
class Soda extends Product { . }
The new class, Soda, automatically contains all of the class members of the Product class. Thus, you can assign values to the $quantity property using the setQuantity() method in Soda, just as you did with the Product class. You can also create new class members to add to the extended class in the class definition. Let's create another example and try this:
<?php include("Product.inc.php");class Soda extends Product { private $ounces; public function __construct($name, $value, $amount, $size) { parent::setDescription($name); parent::setPrice($value); parent::setQuantity($amount); $this->ounces = $size; } public function printProduct() { parent::printProduct(); printf("Size: %.2f ounces<br>\n", $this->ounces); } }$prod1 = new Soda("Root Beer", 1.25, 10, 18);echo "new product added:<br>\n"; $prod1->printProduct();echo "<br>Buying 5 bottles.\n"; $prod1->buyProduct(5); echo "now there's " . $prod1->getQuantity() . " left<br>\n"; $prod1->printProduct(); ?>
class Soda extends Product { private $ounces;
public function __construct($name, $value, $amount, $size) { parent::setDescription($name); parent::setPrice($value); parent::setQuantity($amount); $this->ounces = $size; }
public function printProduct() { parent::printProduct(); printf("Size: %.2f ounces<br>\n", $this->ounces); } }
$prod1 = new Soda("Root Beer", 1.25, 10, 18);
echo "new product added:<br>\n"; $prod1->printProduct();
echo "<br>Buying 5 bottles.\n"; $prod1->buyProduct(5); echo "now there's " . $prod1->getQuantity() . " left<br>\n"; $prod1->printProduct(); ?>
When you view the Web page in your browser, it should look like this:
Because the Soda class extends the Product class, you must use the include() function to include the Product class definition code before you can write the class extension code. The class Soda extends the Product class by adding a new property ($ounces). Also, it overwrites two existing method members of the Product class: the constructor and the printProduct() method.
Both the constructor and printProduct() methods use another odd feature of OOP. The double colon symbol (its official name is the scope resolution operator) allows access to the parent properties and methods from the child class. In this example, I use the get series of methods from the Product class to assign values to the properties contained in the parent. To reference the properties in the parent, you must specifically point to the parent methods using the scope resolution operator:
parent::setDescription($name);
You use the same technique to print the parent properties using the printProduct() method. The only thing the child printProduct() method must add is print the $ounces property.
Using OOP With Your Database
As you've seen throughout this course, the PHP MySQL extension provides lots of functions for interacting with a MySQL server. However, all of these functions use the procedural style of programming. If you're using OOP to create your application, you won't want to mix OOP code with procedural code just to connect with your database.
To resolve this problem, PHP includes another extension package, the MySQL Improved extension (called php_mysqli). The php_mysqli extension provides both OOP classes and procedural functions for connecting to the database, submitting queries, and retrieving result sets. The great thing is that you can use the php_mysqli extension as a parent class and create your own customized methods for submitting queries and retrieving your data. This is where the real power of OOP comes into play!
Note: To use the php_mysqli extension, you must have it installed and activated on your AMP server. The WampServer already has this extension installed and activated. If you're following along on another server, follow the procedure for activating an extension on your server.
The MySQL Improved extension uses the PHP class called mysqli. The basic format for connecting to a MySQL database, submitting a query, and retrieving the result set using the mysqli class is:
$con = new mysqli("localhost", "test", "test", "store"); $query = "SELECT description, price, quantity FROM products"; $result = $con->query($query); while( $row = $result->fetch_assoc()) { $description = $row['description']; $price = $row['price']; $quantity = $row['quantity']; }
The process is similar to the mysql_ functions we've used in this course but with an OOP twist.
Combining It All Together
Now let's really take a dive into the OOP world. For the last example, you'll extend the mysqli class to create your own database methods that are specialized to your application environment. First, you need to create your new class, called ProductDatabase:
Print code
<?php include("Product.inc.php");class ProductDatabase extends mysqli { public function clean_and_query($query) { if (get_magic_quotes_gpc()) $query = stripslashes($query); $query = $this->real_escape_string($query); return $this->query($query); } public function getProduct($result) { if ($row = $result->fetch_assoc()) { $prod = new Product($row['description'], $row['price'], $row['quantity']); return $prod; } else { return FALSE; } } } ?>
class ProductDatabase extends mysqli {
public function clean_and_query($query) { if (get_magic_quotes_gpc()) $query = stripslashes($query); $query = $this->real_escape_string($query); return $this->query($query); }
public function getProduct($result) { if ($row = $result->fetch_assoc()) { $prod = new Product($row['description'], $row['price'], $row['quantity']); return $prod; } else { return FALSE; } } } ?>
By default, your ProductDatabase class inherits all of the standard methods and properties of the mysqli class, so we'll be able to use the query() and fetch_assoc() methods as normal. This class creates a new method, called clean_and_query(). The purpose of this specialized class is to remove any added slashes by the magic_quotes_gpc feature, and then it uses the mysqli version of the mysql_real_escape_string() function to add any slashes to trouble characters.
The getProducts() method is even trickier. It receives the result of a mysqli query, then processes it in a mysqli fetch_assoc() method. The trick is it puts the returned result in a Product class object for you. This lets you use the methods you created in the Product class to process your product data. Awesome!
Now you can create an application that uses your new class. Follow these steps:
<?phpinclude("ProductDatabase.inc.php");$con = new ProductDatabase("localhost", "test", "test", "store"); $query = "SELECT description, price, quantity FROM products"; $result = $con->clean_and_query($query);while ( $product = $con->getProduct($result)) { $product->printProduct(); echo "----------------------<br>\n"; } ?>
include("ProductDatabase.inc.php");
$con = new ProductDatabase("localhost", "test", "test", "store"); $query = "SELECT description, price, quantity FROM products"; $result = $con->clean_and_query($query);
while ( $product = $con->getProduct($result)) { $product->printProduct(); echo "----------------------<br>\n"; } ?>
You should see the output of all the records in your products table.
To use your new class, you must instantiate a new object using the ProductDatabase() constructor. Since it inherits the mysqli class, you can use the same constructor format. Then, use your new clean_and_query() function to submit your database query, and send the results to your new getProducts() method. Then the code uses the printProduct() method to easily display the product information.
It's a great way to build your code library with classes that you can use over and over again. Now, let's go on to Chapter 5 and wrap up this lesson.
Summary
The PHP language is a great way to test the object-oriented programming waters without having to learn a whole new language. You can leverage your existing PHP programming skills and build applications using OOP principles.
Today you learned how to create a basic OOP class using PHP and then use that class to create objects in an application. The class can contain any number of property and method members. You can define each member to be private only for the class or for public use outside of the class code.
You also discovered how to extend an existing class into a new class using the extends keyword. This enables you to build onto existing classes that you or other programmers have created.
Finally, you found out how to use the extension feature to extend a standard PHP library class, the mysqli class. The mysqli class provides standard methods for submitting queries to a MySQL server and retrieving the result set. You built a sample class that extends the mysqli class to add your own features.
You still have a quiz and an assignment for this last lesson; so before diving into the final exam for the course, please allow some time to do those first. Also, if you haven't already checked out the book recommendations under the Resources link, I would encourage you to do that as well. One of the exciting things about PHP and MySQL is that there is always something more to learn!
When you feel you're ready to take the final exam, click the Completion link at the top or bottom of any page in this classroom. The exam is open-book, so feel free to print your notes or have the classroom open in another window for easy reference. Also, you may print the final exam before taking it for additional study. Please take your time, because you get only one chance at the final. When you finish, be sure to print your completion letter.
Last, I would appreciate it very much if you would take some time to evaluate this course. I pay close attention to my students' feedback; your input helps me tremendously as I continually fine-tune and improve this course material. So if you have any suggestions, comments, or concerns, please include those in your evaluation. If you'd like a response, please also post your comments or questions in the Discussion Area for this lesson.
Final Steps
Now that you've finished the last lesson, is there anything else to do? Yes, several things!
Other Courses
If you enjoyed this course, here are a few other online courses you might be interested in:
Introduction to SQL SQL is the language understood by the database server. Knowing how to write proper SQL queries can make the difference between creating a blazing-fast Web site and a ridiculously slow Web site. This course guides you through the basic structure of relational databases, how to read and write simple SQL statements, and advanced data manipulation techniques—all of which are crucial elements to a successful dynamic Web page.
Designing Effective Web Sites Creating a dynamic Web site isn't all about the PHP code. There are plenty of other elements involved in creating a successful Web site. This course will help you become familiar with good user interface design techniques that will allow your visitors to navigate your site with ease.
If you enjoyed this course, here are a few other ed2go online courses you might be interested in:
This section of the PHP online manual describes all of the OOP features implemented in PHP 5.x.
This is another section of the PHP online manual that describes all of the OOP features implemented in PHP 4.x. There are a few subtle differences; so be careful!
Back to top